<template>
  <div>
    <t-popconfirm :visible="visible" theme="danger" hover="color" :confirm-btn="{ size: 'medium', content: '确定' }" :cancel-btn="{ size: 'medium' }"
                  @visible-change="onVisibleChange" @confirm="warehouseAdd" @cancel="warehouseAddCancel">
      <template #icon><p></p></template>
      <template #content>
        <div style="width: 400px;">
          <h3 class="popconfirm-title">新建仓库</h3>
          <div class="mt16">
            <t-form :data="formData" :rules="rules" ref="optionForm" label-align="top" @submit="warehouseAddConfirm">
              <t-form-item label="仓库类型" name="w_type">
                <t-radio-group v-model="formData.w_type" :options="options"></t-radio-group>
              </t-form-item>
              <t-form-item label="名称" name="name">
                <t-input v-model="formData.name" placeholder="请输入名称"></t-input>
              </t-form-item>
            </t-form>
          </div>
        </div>
      </template>
      <t-button theme="primary" variant="text" block>新建仓库</t-button>
    </t-popconfirm>
  </div>
</template>

<script>
import {warehouseCreateApi} from "@/api/warehouse";

export default {
  name: 'AddStore',
  data() {
    return {
      visible: false,
      formData: {
        name: '',
        w_type: 1, // 仓库类型
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      options: [
        // （0 平台库；1 代理商库；）
        {label: '代理商库', value: 1},
        {label: '平台库', value: 0},
      ],
    }
  },
  methods: {
    // 添加仓库
    warehouseAdd() {
      this.$refs.optionForm.submit()
    },
    // 取消添加仓库
    warehouseAddCancel() {
      this.formData = {
        name: '',
        w_type: 1, // 仓库类型
      }
      this.$refs.optionForm.reset()
    },
    onVisibleChange(val, context = {}) {
      // trigger 表示触发来源，可以根据触发来源自由控制 visible
      if (context && context.trigger !== 'confirm') {
        this.visible = val;
        this.formData = {
          name: '',
          w_type: 1, // 仓库类型
        }
      }
    },
    // 确定添加仓库
    warehouseAddConfirm({ validateResult, firstError }) {
      if (validateResult === true) {
        warehouseCreateApi(this.formData).then(res=> {
          this.$message.success('添加成功')
          this.formData = {
            name: '',
            w_type: 1, // 仓库类型
          }
          this.$refs.optionForm.reset()
          this.visible = false
          this.$emit('refresh')
        }).catch(err=> {
          console.log(err)
        })
      } else {
        this.$message.warning(firstError);
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>
